<?php
/**
 * 创建人 : Forpastime
 * 创建时间: 2023/4/21 16:46
 * 个人主页 : http://forpastime.com
 */

namespace App\Controller\Admin;

use App\Utils\Result;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use App\Annotation\AdminNode;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use App\Middleware\Auth\AdminTokenMiddleware;
use App\Middleware\Auth\AdminPowerMiddleware;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;

/**
 * @AdminNode(name="数据管理", isMenu="1",sort=1,style="layui-icon-template-1")
 * @Middlewares({
 *      @Middleware(AdminTokenMiddleware::class),
 *      @Middleware(AdminPowerMiddleware::class)
 * })
 *
 * @AutoController(prefix="admin/data")
 * Class DataController 数据管理
 * @package App\Controller\Admin
 */
class DataController
{
    /**
     * @Inject()
     * @var RequestInterface
     */
    protected $request;

    /**
     * @AdminNode(name="数据表列表", isMenu="1")
     */
    public function index()
    {
        $tables = Db::select("show tables");
        $data = [];
        foreach ($tables as $key => $val){
            $data[$key]['table_name'] = $val['Tables_in_'.env('DB_DATABASE')];
//            $countSql = "select count(*) as records from ".$val['Tables_in_'.env('DB_DATABASE')].";";
//            $data[$key]['records'] = Db::select($countSql)[0]['records'];
        }
        return Result::success($data);
    }

    /**
     * @AdminNode(name="备份记录", isMenu="1")
     */
    public function backupRecord(RequestInterface $request)
    {
        $params = $request->all();
        $where = [];
        if(isset($params['table_name']) && $params['table_name']!="false"){
            $where[] = ['table_name','=',$params['table_name']];
        }
        $list = Db::table('data_backup_record')->where($where)->paginate(intval($params['limit']));
        return Result::success(for_paginator_data_formater($list));
    }

    /**
     * @AdminNode(name="备份数据")
     */
    public function backup(RequestInterface $request)
    {
        set_time_limit(0);
        $todayPath=BASE_PATH.'/data/backup/'.date("Ymd").'/';
        if(!is_dir($todayPath)){
            mkdir($todayPath);
        }

        $params = $request->all();
        $tableName = $params['table_name'];
        if(empty($tableName)){
            return Result::error('参数异常');
        }

        $sql = "SET FOREIGN_KEY_CHECKS=0;\r\n";//取消外键约束
        $sql .= "DROP TABLE IF EXISTS `$tableName`;\r\n";
        $createSql = Db::select("SHOW CREATE TABLE `$tableName`");
        $sql .= $createSql[0]['Create Table'].";\r\n";
        $sql .= ";\r\n";

        $dump = Db::select("SELECT * FROM `$tableName`");

        foreach($dump as $k => $v){
            $keys = array_keys($v);
            $keys = array_map('addslashes', $keys);
            $keys = join('`,`', $keys);
            $keys = "`" . $keys . "`";
            $vals = array_values($v);
            $vals = array_map('addslashes', $vals);
            $vals = join("','", $vals);
            $vals = "'" . $vals . "'";
            $sql .= "INSERT INTO `$tableName` ($keys) VALUES ($vals);\r\n";
        }

        $sqlFile = $todayPath.$tableName.'.sql';
        if(!file_exists($sqlFile)){
            touch($sqlFile);
        }
        $res = file_put_contents($sqlFile,$sql);
        if($res){
            Db::select("INSERT INTO for_data_backup_record (created_at,table_name,admin,records) VALUES (?,?,?,?)",[date("Y-m-d H:i:s"),$tableName,$params['admin'],sizeof($dump)]);
            return Result::success();
        }else{
            return Result::error();
        }
    }

    /**
     * @AdminNode(name="恢复备份")
     */
    public function recovery()
    {
        set_time_limit(0);
        $params = $this->request->all();
        $tableName = $params['table_name'];
        if(empty($tableName)){
            return Result::error('参数异常');
        }

        $sqlFile = BASE_PATH.'/data/backup/'.date('Ymd',strtotime($params['created_at'])) .'/'. $tableName . ".sql";
        if(!file_exists($sqlFile)){
            return Result::error('该备份记录文件不存在');
        }

        $sqls = for_split_sql($sqlFile,env('DB_PREFIX','for_'));

        foreach ($sqls as $key => $sql) {
            if(empty(trim($sql))){
                continue;
            }
            try {

                Db::select($sql);
            } catch (\Throwable $throwable) {
                var_dump(get_class($throwable), $throwable->getMessage());
                return Result::error($throwable->getMessage());
            }
        }

        return Result::success();
    }

    /**
     * @AdminNode(name="导出备份")
     */
    public function export(ResponseInterface $response):Psr7ResponseInterface
    {
        set_time_limit(0);
        $params = $this->request->all();
        $tableName = $params['table_name'];
        if(empty($tableName)){
            return Result::error('参数异常');
        }
        $sqlFile = BASE_PATH.'/data/backup/'.date('Ymd',strtotime($params['created_at'])) .'/'. $tableName . ".sql";
        if(!file_exists($sqlFile)){
            return Result::error('该备份记录文件不存在');
        }


        return $response->download($sqlFile,$tableName . ".sql");
        //return $response->download(BASE_PATH.'/public/static/images/a1.jpg');b826926e78b039be4006135bc705dfca.doc
        //return $response->download(BASE_PATH.'/public/uploads/20230410/b826926e78b039be4006135bc705dfca.doc');
    }
}